package com.qfedu.web;

import com.qfedu.model.User;
import com.qfedu.service.UserService;
import com.qfedu.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * Title: UserServlet
 *
 * @author Wenn.
 * @Package com.qfedu.web
 * @Date 2023/4/18 19:44
 * @Note
 */
@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //注册业务实现
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        //先判断验证码
        String code = req.getParameter("code");
        //从session中取出验证码
        HttpSession session = req.getSession();

        String attribute = (String) session.getAttribute("KAPTCHA_SESSION_KEY");
        //验证码不正确
        resp.setContentType("text/html;charset=utf-8");
        if (!attribute.equalsIgnoreCase(code)) {
            //保存到request域中
            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", username);
            req.setAttribute("email", email);
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
        //完成注册
        User user = new User(username, password, email);
        int row = userService.regist(user);
        if (row > 0) {

            //注册成功
            session.setAttribute("user", user);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            req.setAttribute("msg", "注册失败，请重试！！");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }

    }

    //校验用户名servlet
    public void checkName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean flag = userService.checkUser(username);
        resp.setContentType("text/html;charset=utf-8");
        if (flag) {//用户名已存在
            resp.getWriter().write("用户名已经存在");
        } else {
            resp.getWriter().write("用户名可以注册");
        }

    }

    //登录功能
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //调用业务层实现
        User user1 = userService.login(user);
        if (user1 != null) {
            //登录成功 保存到session
            req.getSession().setAttribute("user", user1);
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        } else {
            //登录失败
            req.setAttribute("username", username);//做数据的回显
            resp.setContentType("text/html;charset=utf-8");
            req.setAttribute("msg", "用户名或者密码错误");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        }
    }

    //退出
    public void loginOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁session  重新进入到登录页面
        req.getSession().invalidate();
        req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
    }

    //用户修改
    public void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        try {
            //获取参数
            Map<String, String[]> parameterMap = req.getParameterMap();
            User user = new User();
            BeanUtils.populate(user,parameterMap);
            //调用业务层完成操作
            UserService userService = new UserServiceImpl();
            int row =  userService.updateUser(user);
            if (row>0){
                //修改成功
                req.getRequestDispatcher("/userServlet?action=findUserById").forward(req,resp);
            }else {
                //修改失败 跳转到错误页面
                req.setAttribute("message","修改失败，请重新操作");
                req.getRequestDispatcher("/error.jsp").forward(req,resp);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //根据id修改
    public void findUserById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //获取参数
        String parameter = req.getParameter("id");
        int id = Integer.parseInt(parameter);
        //调用业务层查询
        UserService userService = new UserServiceImpl();
        User user = userService.findUserById(id);
        if (user!=null){
            //查询成功
            req.setAttribute("user",user);
            req.getRequestDispatcher("/pages/user/update.jsp").forward(req,resp);
        }else {
            //查询失败 跳转到错误页面
            req.setAttribute("message","查询失败，请重新操作");
            req.getRequestDispatcher("/error.jsp").forward(req,resp);
        }
    }

}